<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
    <script src="https://cdn.staticfile.org/vue/2.7.0/vue.min.js"></script>
    <!-- 【1.1】引入核心文件 -->
    <script src="./js/recorder-core.js"></script>

    <!-- 【1.2】引入相应格式支持文件；如果需要多个格式支持，把这些格式的编码引擎js文件放到后面统统加载进来即可 -->
    <script src="./js/engine/mp3.js"></script>
    <script src="./js/engine/mp3-engine.js"></script>
</head>

<body>
    <div id="app">
        <p>{{ message }}</p>
        <button @click="audioOpen">准备录音</button>
        <button @click="audioStart">开始录音</button>
        <button @click="stopAudio">停止录音</button>
        <button @click="playAudio">播放录音</button>
    </div>

    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    message: 'Hello Vue.js!',
                    audioSrc: "",
                    recorder: null,
                    recBlob: null,
                    ws: null,
                };
            },

            methods: {
                audio() {
                    // 开始录音
                    console.log("start");
                    this.recorder.start().then(() => {
                        // 开始录音

                    }, (error) => {
                        // 出错了
                        console.log(`${error.name} : ${error.message}`);
                    });
                },
                stopAudio() {
                    this.recorder.stop((blob, duration) => {
                        this.audioSrc = (window.URL || webkitURL).createObjectURL(blob);
                        console.log(blob, this.audioSrc, "时长:" + duration + "ms");
                        console.log("blob----------", this.audioSrc);
                        this.recBlob = blob;
                        console.log("已录制mp3：" + this.recBlob + "字节，可以点击播放、上传了", 2);
                    }, function (msg) {
                        console.log("录音失败:" + msg, 1);
                    });

                },
                playAudio() {
                    console.log("play")
                    var audio = document.createElement("audio");
                    audio.controls = true;
                    audio.src = this.audioSrc;
                    audio.play();

                    setTimeout(function () {
                        (window.URL || webkitURL).revokeObjectURL(audio.src);
                    }, 5000);
                },
                audioOpen() {
                    // create ws
                    const url = `ws://118.195.186.158:50080/wss/asr/v1/streaming_recognize`
                    let option = {
                        headers: {
                            Appid: "ld_yani_customer_640480",
                            Authorization: "e1LsOmGeDULFrdDfC1fk6DpnKjuuEc0O"
                        }
                    }
                    // var ws = new WebSocket(url, option);
                    this.ws = new WebSocket(url);
                    this.ws.onopen = (e) => {
                        //成功连接服务器回调
                        console.log('客户端（client）：与服务器的连接已打开')
                        // 发送配置
                        let config = '{"interim_results":true,"config":{"language_code":"zh-cmn-Hans-CN","sample_rate_hertz":16000,"encoding":"LINEAR16"}}';
                        this.ws.send(config);
                        // ws.send(config);
                    }
                    this.ws.onmessage = (e) => {
                        // console.log("-------onmessage---",e);
                        if (typeof e.data === "string") {
                            console.log("************String message received", e.data);
                        } else {
                            console.log("***************------------Other message received", e, e.data);
                        }
                    }
                    this.ws.onerror = function (e) {
                        console.log("WebSocket Error: ", e);
                    };

                    this.ws.onclose = (e) => {
                        console.log("-------close---，录音结束");
                        // stop();
                        this.stopAudio()
                    }
                    console.log("open...........", this.recorder);
                    let tempIndex = 0;
                    let rec = new Recorder({
                        type: "mp3", sampleRate: 16000, bitRate: 16 //mp3格式，指定采样率hz、比特率kbps，其他参数使用默认配置；注意：是数字的参数必须提供数字，不要用字符串；需要使用的type类型，需提前把格式支持文件加载进来，比如使用wav格式需要提前加载wav.js编码引擎
                        , onProcess: (buffers, powerLevel, bufferDuration, bufferSampleRate, newBufferIdx, asyncEnd) => {
                            //录音实时回调，大约1秒调用12次本回调
                            tempIndex++;
                            // console.log(ws.readyState,"--callback,", buffers);
                            if (tempIndex % 4 == 0) {
                                if (this.ws.readyState === WebSocket.OPEN) {
                                    for (let index = 0; index < buffers.length; index++) {
                                        const int16Arr = buffers[index];
                                        this.ws.send(int16Arr.buffer)
                                    }

                                } else {
                                    console.log("ws closed............");
                                }
                            }
                        }
                    })
                    this.recorder = rec;
                    this.recorder.open();

                },
                audioStart() {
                    console.log("start...........");
                    this.recorder.start();
                },
            }
        })
    </script>
</body>

</html>